//
//  TakePhotoTool.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/9/8.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "TakePhotoTool.h"
#import "UIActionSheet+Extension.h"
#import "SZLTabBarViewController.h"
#import "WaterRippleWait.h"
#import "PersonNetWork.h"
#import "CropImageViewController.h"
#import "HXCutPictureViewController.h"
#import "MBProgressHUD+MJ.h"

@interface TakePhotoTool()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) selectImageBlock selectBlock;
@property (nonatomic,assign) CGFloat scale;

@end

@implementation TakePhotoTool

static TakePhotoTool *_tool;
+ (instancetype)shareTool
{
    if (!_tool) {
        _tool = [[TakePhotoTool alloc]init];
    }
    return _tool;
}

//更换头像
- (void)beginSelectWithScale:(CGFloat)scale image:(selectImageBlock)block
{
    self.selectBlock = block;
    self.scale = scale;
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选取",@"拍照", nil];
    SZLTabBarViewController *barVc = (SZLTabBarViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *vc = barVc.childViewControllers[3];
    [sheet showInView:[UIApplication sharedApplication].keyWindow];
    [sheet handlerClickedButton:^(UIActionSheet *actionSheet, NSInteger btnIndex) {
        if (btnIndex == 0) {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePicker.allowsEditing = NO;
            imagePicker.delegate = self;
            [vc presentViewController:imagePicker animated:YES completion:nil];
        }else if (btnIndex == 1){
            BOOL isCameraSupport = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
            if (!isCameraSupport) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"相机不可用,请检查相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }else{
                UIImagePickerController *cameraPicker = [[UIImagePickerController alloc]init];
                cameraPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                cameraPicker.allowsEditing = NO;
                [vc presentViewController:cameraPicker animated:YES completion:nil];
                cameraPicker.delegate = self;
            }
        }
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *selectPhoto = info[@"UIImagePickerControllerOriginalImage"];
    SZLTabBarViewController *barVc = (SZLTabBarViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UINavigationController *navVc = barVc.selectedViewController;
    if (self.scale) {
        HXCutPictureViewController *vc = [[HXCutPictureViewController alloc] initWithCropImage:selectPhoto  cropSize:CGSizeMake(ScreenW, ScreenW/self.scale) title:@"裁剪" isLast:YES];
        vc.completion = ^(HXCutPictureViewController *vc, UIImage *finishImage) {
            [self upLoadFile:finishImage];
        };
        [navVc pushViewController:vc animated:YES];
    }else {
        [self upLoadFile:selectPhoto];
    }
    [navVc dismissViewControllerAnimated:YES completion:nil];
}

- (void)upLoadFile:(UIImage *)image
{
    __WEAK
    UIImage *imageNew = [self imageByScalingAndCroppingForSize:image.size withSourceImage:image];
    [self showWaiter];
    [PersonNetWork upLoadImageWithParame:@{@"optionType":@"1"} image:imageNew response:^(BOOL success, NSString *msg,NSString *path) {
        [weakSelf hideWaiter];
        if (success) {
            self.selectBlock(image,path);
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withSourceImage:(UIImage *)sourceImage
{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    
    return newImage;
}
- (void)showWaiter
{
    [WaterRippleWait waterRippleShowBackgroundColor:[UIColor clearColor]];
}
- (void)hideWaiter
{
    [WaterRippleWait hideWaterRipple];
}

@end
